<template>
  <div class="common-layout">
    <el-container>
      <el-main>
        <div class="main flex">
          <div class="flex-1 ml-4">
            <el-form ref="formRef" :inline="true" :model="form">
              <el-form-item label="学生姓名：" prop="Name">
                <el-input v-model="form.Name" placeholder="请输入学生姓名" clearable @keyup.enter="getlist" />
              </el-form-item>
              <el-form-item label="学生编号：" prop="No">
                <el-input v-model="form.No" placeholder="请输入学生编号" clearable @keyup.enter="getlist" />
              </el-form-item>
              <el-form-item>
                <el-button type="primary" :icon="Search" @click="getlist">搜索</el-button>
                <el-button :icon="Refresh" @click="resetForm">重置</el-button>
              </el-form-item>
            </el-form>

            <div class="common-layout-2">
              <el-container>
                <el-header style="text-align: right" height="80px">
                  <el-row>
                    <el-col :span="12">
                      <h1 class="main-title">学生管理</h1>
                    </el-col>
                    <el-col :span="12">
                      <el-button type="primary" :icon="Plus" @click="showAddDialog">
                        新增学生
                      </el-button>
                    </el-col>
                  </el-row>
                </el-header>
                <el-main>
                  <el-scrollbar :height="isWidth ? '630px' : '419px'">
                    <el-table table-layout="auto" :size="size" :data="datalist" :header-cell-style="{
                      background: '#fafafa',
                      color: '#606266',
                    }" border stripe v-loading="loading" element-loading-background="rgba(255, 255, 255, .5)"
                      element-loading-text="加载中，请稍后..." element-loading-spinner="el-icon-loading"
                      :default-sort="{ prop: 'No', order: 'acending' }">
                      <el-table-column prop="No" align="center" label="编号" />
                      <el-table-column prop="Password" align="center" label="密码" />
                      <el-table-column prop="Name" align="center" label="姓名" />
                      <el-table-column prop="Sex" align="center" label="性别" />
                      <el-table-column prop="Age" align="center" label="年龄" />
                      <el-table-column prop="Num" align="center" label="测试次数" />
                      <el-table-column fixed="right" align="center" label="操作" width="180">
                        <template #default="scope">
                          <el-button class="reset-margin" link type="primary" :size="size" @click="
                            showModDialog(
                              scope.row.No,
                              scope.row.Name,
                              scope.row.Sex,
                              scope.row.Age,
                              scope.row.Password
                            )
                          ">
                            修改
                          </el-button>
                          <el-button class="reset-margin" link type="primary" :size="size"
                            @click="delStudent(scope.row.No)">
                            删除
                          </el-button>
                        </template>
                      </el-table-column>
                    </el-table>
                  </el-scrollbar>
                </el-main>
              </el-container>
            </div>
          </div>
        </div>
      </el-main>
    </el-container>
  </div>
  <el-dialog title="添加学生" v-model="addDialog" width="20%" draggable>
    <el-form :model="addForm" :rules="addFormRules" label-width="100px">
      <el-form-item label="选择班级" prop="ID">
        <el-select v-model="addForm.ID" class="m-2" placeholder="Select">
          <el-option v-for="item in classlist" :key="item.No" :label="item.Name" :value="item.No" />
        </el-select>
      </el-form-item>
      <el-form-item label="学生编号" prop="No">
        <el-input v-model="addForm.No" placeholder="01、02..."></el-input>
      </el-form-item>
      <el-form-item label="学生姓名" prop="Name">
        <el-input v-model="addForm.Name"></el-input>
      </el-form-item>
      <el-form-item label="学生性别" prop="Sex">
        <el-radio-group v-model="addForm.Sex" class="ml-4">
          <el-radio label="男" size="small">男</el-radio>
          <el-radio label="女" size="small">女</el-radio>
        </el-radio-group>
      </el-form-item>
      <el-form-item label="学生年龄" prop="Age">
        <el-input v-model="addForm.Age"></el-input>
      </el-form-item>
    </el-form>
    <span class="dialog-footer" style="margin-left: 38%" draggable>
      <el-button type="primary" @click="addStudent()">确 定</el-button>
      <el-button @click="addDialog = false">取 消</el-button>
    </span>
  </el-dialog>
  <el-dialog title="修改学生" v-model="modDialog" width="20%">
    <el-row>注：不更改则默认为原值</el-row><br />
    <el-form :model="modForm" :rules="FormRules" label-width="100px">
      <el-form-item label="选择班级" prop="ID">
        <el-select v-model="modForm.ID" class="m-2" :placeholder="preClass">
          <el-option v-for="item in classlist" :key="item.No" :label="item.Name" :value="item.No" />
        </el-select>
      </el-form-item>
      <el-form-item label="更改姓名" prop="Name">
        <el-input v-model="modForm.Name" :placeholder="preName"></el-input>
      </el-form-item>
      <el-form-item label="更改密码" prop="Pwd">
        <el-input v-model="modForm.Pwd" :placeholder="prePwd"></el-input>
      </el-form-item>
      <el-form-item label="学生性别" prop="Sex">
        <el-radio-group v-model="modForm.Sex" class="ml-4">
          <el-radio label="男" size="small">男</el-radio>
          <el-radio label="女" size="small">女</el-radio>
        </el-radio-group>
      </el-form-item>
      <el-form-item label="学生年龄" prop="Age">
        <el-input v-model="modForm.Age" :placeholder="preAge"></el-input>
      </el-form-item>
    </el-form>
    <span class="dialog-footer" style="margin-left: 38%">
      <el-button type="primary" @click="modStudent()">确 定</el-button>
      <el-button @click="modDialog = false">取 消</el-button>
    </span>
  </el-dialog>
</template>

<script>
import { Refresh, Search, Plus } from "@element-plus/icons-vue";
export default {
  data() {
    return {
      form: {
        No: "",
        Name: "",
      },
      addForm: {
        No: "",
        ID: "",
        Name: "",
        Sex: "",
        Age: "",
      },
      modForm: {
        No: "",
        Name: "",
        ID: "",
        Sex: "",
        Age: "",
        Pwd: "",
      },
      addFormRules: {
        No: [
          {
            required: true,
            message: "请输入学生编号",
            trigger: "blur",
          },
        ],
        Name: [
          {
            required: true,
            message: "请输入学院名称",
            trigger: "blur",
          },
        ],
        ID: [
          {
            required: true,
            message: "请选择班级",
            trigger: "blur",
          },
        ],
        Sex: [
          {
            required: true,
            message: "请选择学生性别",
            trigger: "blur",
          },
        ],
        Age: [
          {
            required: true,
            message: "请输入学生年龄",
            trigger: "blur",
          },
        ],
      },
      preNo: "",
      preName: "",
      preAge: "",
      prePwd: "",
      preClass: "",
      preID: "",
      datalist: [],
      resultlist: [],
      classlist: [],
      Search,
      Refresh,
      Plus,
      loading: true,
      addDialog: false,
      modDialog: false,
      screenWidth: document.body.clientWidth,
      isWidth: false
    };
  },
  mounted() {
    this.setClient();
    this.getall();
  },
  methods: {
    async getlist() {
      this.loading = true;
      this.datalist = [];
      if (this.form.Name === "") {
        const { data: res } = await this.$http.post(
          "api/query/studentNo",
          this.form
        );
        if (res.Data["res"][0].Code === 200) {
          this.datalist = res.Data["res"];
        }
        const { data: ret } = await this.$http.post("api/query/result", {
          Sno: "",
          Pno: "",
        });
        this.resultlist = ret.Data["ret"];
        for (var i = 0; i < this.datalist.length; i++) {
          var num = 0;
          for (var j = 0; j < this.resultlist.length; j++) {
            if (this.datalist[i]["No"] == this.resultlist[j]["Sno"]) {
              num += 1;
            }
          }
          this.datalist[i]["Num"] = num;
        }
      } else {
        const { data: res } = await this.$http.post(
          "api/query/studentName",
          this.form
        );
        if (res.Data["res"][0].Code === 200) {
          this.datalist = res.Data["res"];
        }
        const { data: ret } = await this.$http.post("api/query/result", {
          Sno: "",
          Pno: "",
        });
        this.resultlist = ret.Data["ret"];
        for (i = 0; i < this.datalist.length; i++) {
          num = 0;
          for (j = 0; j < this.resultlist.length; j++) {
            if (this.datalist[i]["No"] == this.resultlist[j]["Sno"]) {
              num += 1;
            }
          }
          this.datalist[i]["Num"] = num;
        }
      }
      this.loading = false;
    },
    async getall() {
      this.loading = true;
      this.datalist = [];
      this.resultlist = [];
      this.classlist = [];
      const { data: res } = await this.$http.post("api/query/studentAll");
      this.datalist = res.Data["ret"];
      const { data: ret } = await this.$http.post("api/query/result", {
        Sno: "",
        Pno: "",
      });
      this.resultlist = ret.Data["ret"];
      for (var i = 0; i < this.datalist.length; i++) {
        var num = 0;
        for (var j = 0; j < this.resultlist.length; j++) {
          if (this.datalist[i]["No"] == this.resultlist[j]["Sno"]) {
            num += 1;
          }
        }
        this.datalist[i]["Num"] = num;
      }
      const { data: rep } = await this.$http.post("api/query/classAll", {});
      this.classlist = rep.Data["ret"];
      this.loading = false;
    },
    resetForm() {
      this.form.Name = "";
      this.form.No = "";
      this.getall();
    },
    async delStudent(No) {
      const confirmResult = await this.$confirm(
        "将永久删除该学生, 是否继续?",
        "提示",
        {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning",
        }
      ).catch((err) => err);
      if (confirmResult != "confirm") {
        return this.$message.info("已取消删除");
      }
      const { data: res } = await this.$http.post("api/delete/student", {
        No: No,
      });
      if (res.Data["res"][0].Code != 200) {
        return this.$message.error("删除失败 T.T 请先删除该学生的其他信息。");
      } else {
        this.$message.success("删除成功");
        this.getall();
      }
    },
    showAddDialog() {
      this.addForm = {};
      this.addDialog = true;
    },
    async addStudent() {
      // if (this.addForm.Pwd == "") this.addForm.Pwd =
      this.addForm["Pwd"] = this.addForm.ID + this.addForm.No;
      const { data: res } = await this.$http.post("api/query/studentNo", {
        No: this.addForm.ID + this.addForm.No,
      });
      if (res.Data["res"][0].Code == 200) {
        this.addForm = {};
        return this.$message.error("添加失败 T.T 编号被别的学生抢先了");
      } else {
        this.addForm.Age = parseInt(this.addForm.Age);
        const { data: res } = await this.$http.post(
          "api/insert/student",
          this.addForm
        );
        if (res.Data["res"][0].Code == 200) {
          this.getall();
          this.addDialog = false;
          this.$message.success("增加成功");
        }
      }
    },
    showModDialog(No, Name, Sex, Age, Pwd) {
      this.modForm.No = "";
      this.modForm.Name = "";
      this.modForm.Age = "";
      this.modForm.Pwd = "";
      this.modForm.ID = "";
      this.modForm.Sex = Sex;
      this.preNo = No.substring(8, 10);
      this.preName = Name;
      this.preAge = Age;
      this.prePwd = Pwd;
      for (var i = 0; i < this.classlist.length; i++) {
        if (this.classlist[i]["No"] == No.substring(0, 8)) {
          this.preClass = this.classlist[i]["Name"];
          this.preID = this.classlist[i]["No"];
          break;
        }
      }
      this.modDialog = true;
    },
    async modStudent() {
      if (this.modForm.Age == "") this.modForm.Age = this.preAge;
      if (this.modForm.Sex == "") this.modForm.Sex = this.preSex;
      if (this.modForm.No == "") this.modForm.No = this.preNo;
      if (this.modForm.ID == "") this.modForm.ID = this.preID;
      if (this.modForm.Pwd == "") this.modForm.Pwd = this.prePwd;
      if (this.modForm.Name == "") this.modForm.Name = this.preName;
      const { data: res } = await this.$http.post("api/query/studentNo", {
        No: this.addForm.ID + this.addForm.No,
      });
      if (res.Data["res"][0].Code == 200) {
        if (res.Data["res"][0].No != this.modForm.No) {
          return this.$message.error("修改失败 T.T 这个编号正在被使用");
        }
      }
      this.modForm.Age = parseInt(this.modForm.Age);
      const { data: ret } = await this.$http.post(
        "api/update/student",
        this.modForm
      );
      if (ret.Data["res"][0].Code == 200) {
        this.getall();
        this.modDialog = false;
        this.$message.success("修改成功");
      } else {
        return this.$message.error("修改失败 T.T");
      }
    },
    setClient() {
      this.screenWidth = document.body.offsetWidth
      console.log(this.screenWidth)
      if (this.screenWidth < 1550) {
        this.isWidth = false
      } else {
        this.isWidth = true
      }
    }
  },
};
</script>

<style lang="less" scoped>
.main-title {
  text-align: left;
  color: rgb(107, 106, 106);
  font-size: 25px;
}

s .common-layout-1 {
  background-color: rgb(255, 255, 255);
  margin: 20px;
}

.common-layout-2 {
  background-color: rgb(255, 255, 255);
}

.common-layout-2 .el-header {
  position: relative;
  color: var(--el-text-color-primary);
}

.common-layout-2 .el-col {
  margin: auto;
  position: relative;
  color: var(--el-text-color-primary);
}
</style>
